package com.tanhua.dubbo.service;

import com.tanhua.model.mongo.Friend;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.MovementTimeLine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @Description: test
 * @Create by: JJ菜菜
 * @Date: 2021/12/2 18:34
 */

@Component
public class TimeLineService {
    /**
     *  为了优化，好友时间线添加，如果有海量数据，就必须采用异步的方式，
     */

    @Autowired
    private MongoTemplate mongoTemplate;

    @Async  // 表名此方法是异步调用方法
    public void saveTimeLine(Movement movement) {

        // 查询好友表，进行时间表的添加
        Criteria criteria = Criteria.where("userId").is(movement.getUserId());
        Query query = Query.query(criteria);
        List<Friend> friends = mongoTemplate.find(query, Friend.class);
        // 循环好友数据构建时间线数据存入数据库
        for (Friend friend : friends) {
            MovementTimeLine movementTimeLine = new MovementTimeLine();
            movementTimeLine.setMovementId(movement.getId());
            movementTimeLine.setFriendId(friend.getFriendId());
            movementTimeLine.setUserId(movement.getUserId());
            movementTimeLine.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend);
        }
    }
}
